<?php

namespace app\apixcx\controller;

use EasyWeChat\Factory;
use app\admin\model\Msg as MsgModel;
use app\admin\model\User as UserModel;
use app\admin\model\Info as InfoModel;

class Msg
{
    protected $MsgModel;
    protected $UserModel;
    protected $InfoModel;

    public function __construct()
    {
        $this->MsgModel = new MsgModel();
        $this->UserModel = new UserModel();
        $this->InfoModel = new InfoModel();
    }

    public function save($mid, $sid, $msg)
    {
        $token = getheaders()['Http-Token'];
        if (!$token || $token != cache('token'.$mid)) {
            return -100;
        }
        $sid = explode('_', $sid)[2];
        $data = [
            'mid' => $mid,
            'sid' => $sid,
            'msg' => $msg,
        ];
        $res = $this->MsgModel->save($data);
        if ($res) {
            // $myUserRes = $this->UserModel->get($mid);
            // $myUserRes -> formid = $formId;
            // $myUserRes -> save();

            $sendUserRes = $this->UserModel->get($sid);

            if ($sendUserRes->openid) {
                $app_id = getheaders()['App-Id'];
                $InfoRes = $this->InfoModel->where('wechatappid', $app_id)->find();
                if ($InfoRes['wechatsecret'] || $InfoRes) {
                    $config = [
                        'app_id' => $InfoRes['wechatappid'],
                        'secret' => $InfoRes['wechatsecret'],
                    ];
                } else {
                    $config = [
                        'app_id' => config('wechat.mini_program.default.app_id'),
                        'secret' => config('wechat.mini_program.default.secret'),
                    ];
                }

                $weChatApp = Factory::miniProgram($config);
                $weChatApp->template_message->send([
                    'touser' => $sendUserRes->openid,
                    'template_id' => 'wA8H8R4hpXasRN-F5hiTQhpJSjWkOL7rV5xaLYaaG30',
                    'page' => 'pages/chat/list',
                    'form_id' => $sendUserRes->formid,
                    'data' => [
                        'keyword1' => $msg,
                        'keyword2' => date('Y-m-d h:i', time()),
                        'keyword3' => '谢谢你给我留言,现在才回复你,不好意思,我现在在线,来和我沟通吧',
                    ],
                ]);
            }

            return 1;
        } else {
            return 0;
        }
    }
}
